package database

import "errors"

// FrozenUser 冻结用户
func FrozenUser(u *User) error {
	db, err := GetDBInstance()
	if err != nil {
		panic(err)
	}
	var user User
	query := db.Table("user").Where("id = ?", u.Id).First(&user)
	if query.RowsAffected <= 0 {
		return errors.New("更新失败，未查询到符合该条件的数据！")
	}
	user.Status = u.Status
	query = query.Save(&user)
	if query.Error != nil {
		return query.Error
	} else if query.RowsAffected > 0 {
		return nil
	} else {
		return errors.New("更新失败，请重试！")
	}
}

type UserPagination struct {
	PageIndex int
	PageSize  int
	Name      string
}

// GetUserList 获取用户列表
func GetUserList(pagination *UserPagination) ([]User, int64) {
	db, err := GetDBInstance()
	if err != nil {
		panic(err)
	}
	var total int64
	query := db.Table("user")
	if len(pagination.Name) > 0 {
		query = query.Where("name LIKE ?", "%"+pagination.Name+"%")
	}
	query.Count(&total)
	var users []User
	offset := (pagination.PageIndex - 1) * pagination.PageSize
	query.Limit(pagination.PageSize).Offset(offset).Find(&users)
	return users, total
}
